<template>
  <div id="writePage" style="position:absolute;width: 100%; height: 100%">
    <van-nav-bar
        left-arrow
        @click-left="onClickLeft"
    >
      <template #right>
        <van-icon name="success" size="large" @click="onSubmit"/>
      </template>
      <template #title>
        <van-popover v-model:show="showPopover" close-on-click-outside>
          <!-- 可以使用 CellGroup 作为容器 -->
          <van-cell-group inset>
            <van-field v-model="title" label="标题" maxlength="16" placeholder="为日记取个名字吧"
                       @click-right-icon="Close"
                       right-icon="success"
            >
            </van-field>
          </van-cell-group>

          <template #reference>
            <van-button v-model="title" :text="title" style="color: darkgray;border-radius: 20px;height: 30%"
                        @click="clearPlaceholder"></van-button>
          </template>
        </van-popover>

      </template>
    </van-nav-bar>

    <div class="uploadImg">
      <van-uploader v-model="fileList"
                    multiple
                    :max-size="2000 * 1024"
                    @oversize="onOversize"
                    :before-read="beforeRead"
                    upload-text="上传图片"
                    :max-count="8"
                    :after-read="afterRead"
      />

    </div>
    <div class="default-box"></div>
    <div class="richBox">
      <QuillEditor v-model:content="content"
                   :placeholder=placeholder
                   :options="editorOptions"
                   contentType="html"
      />
    </div>

  </div>
</template>

<script setup lang="ts">
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import {onMounted, reactive, ref, toRaw} from "vue";
import {useRoute, useRouter} from "vue-router";
import {QuillEditor} from "@vueup/vue-quill";
import {Dialog, Notify, Toast} from "vant";
import {html_encode} from "../utils/tools";
import myAxios, {INDEX_URL} from "../plugins/myAxios";
import {getCurrentUser} from "../services/user";

const router = useRouter();
const route = useRoute();


const showPopover = ref(false)
const title = ref(route.query.title)
const diaryId = ref(route.query.diaryId)

const fileList = ref([])
//todo 将object变为对象数组
let list = route.query.photograph
for (let i = 0; i < list?.length; i++) {
  let item = {
    url: list[i]
  }
  fileList.value.push(item)
}
const placeholder: string = '很喜欢认真记录的你，告诉我今天过得怎么样吧！\n' +
    '你可以用图片文字记录今天。\n'
onMounted(() => {
  getCurrentUser();
})
/**
 * 关闭标题输入框
 * @constructor
 */
const Close = () => {
  if (title.value === '') {
    title.value = '自定义标题'
  }
  showPopover.value = false;
}
/**
 * 清除内容
 */
const clearPlaceholder = () => {
  if (title.value === '自定义标题') {
    title.value = '';
  }
}
const getUrls = () => {
  let array = toRaw(fileList.value);
  return array.map(item => item.url);
}
/**
 * 返回
 */
const onClickLeft = () => {
  router.back();
}
const content = ref(route.query.content);

/**
 * 文件大小超过限制时触发
 * @param file
 */
const onOversize = (file) => {
  Toast('文件大小不能超过 2mb');
}

const beforeRead = (file) => {
  if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
    Toast('请上传 jpg/png 格式图片');
    return false;
  }
  return true;
}
/**
 * 富文本工具设置
 */
const editorOptions = reactive({
  modules: {
    toolbar: [  // 工具栏配置
      ['bold', 'italic', 'underline', 'strike'],  // 粗体、斜体、下划线、删除线
      [{'list': 'ordered'}, {'list': 'bullet'}],  // 有序列表和无序列表
      [{'indent': '-1'}, {'indent': '+1'}],  // 缩进
      [{'direction': 'rtl'}],  // 文字方向
      [{'size': ['small', false, 'large', 'huge']}],  // 字号
      [{'font': []}],  // 字体
      [{'align': []}],  // 对齐方式
      ['clean']  // 清除格式
    ]
  }
})
let formData = new FormData();
formData.append('biz', "diary_photo");
const afterRead = (file) => {
  formData.append('file', file.file);
};
/**
 * 日记修改
 */
let config = {
  headers: {
    "Content-Type": "multipart/form-data"
  }
};
const onSubmit = async () => {
  let text = content.value;
  if (html_encode(text) == '&lt;p&gt;&lt;br&gt;&lt;/p&gt;' && fileList.value.length === 0 && title.value === '自定义标题') {
    Dialog.alert({
      message: '写点内容吧!',
    }).then(() => {
      // on close
    });
  } else {
    if (formData.has('file')) {
      myAxios.post('/file/upload', formData, config)
          .then((res) => {
            if (res.code === 0) {
              formData.delete('file')
              fileList.value = [];
              res.data.map(item => {
                let list = {
                  url: item,
                  deletable: true
                }
                fileList.value.push(list)
              })
              myAxios.post(`/diary/update`, {
                id: diaryId.value,
                photograph: JSON.stringify(getUrls()),
                title: title.value,
                content: text
              })
                  .then((otherRes) => {
                    if (otherRes.code === 0) {
                      console.log('修改成功')
                      Notify({type: 'success', message: '日记已修改'});
                      window.location.href = INDEX_URL;
                    } else {
                      Toast.fail(otherRes.message);
                    }
                  })
            }
          })
    } else {
      myAxios.post(`/diary/update`, {
        id: diaryId.value,
        photograph: JSON.stringify(getUrls()),
        title: title.value,
        content: text
      })
          .then((res) => {
            if (res.code === 0) {
              Notify({type: 'success', message: '日记已修改'});
              window.location.href = INDEX_URL;
            }
          })
    }
  }
}
</script>

<style scoped>
.uploadImg {
  margin-left: 6%;
  margin-top: 4%;
}

.richBox {
  height: 57%;
}
</style>